package com.sdhs.system.syncdata.service.impl;

import cn.hutool.json.JSONUtil;
import com.banboocloud.Codec.BamboocloudFacade;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.system.service.impl.SysUserServiceImpl;
import com.sdhs.system.syncdata.domain.SyncSysUser;
import com.sdhs.system.syncdata.mapper.SyncSysRoleUserMapper;
import com.sdhs.system.syncdata.mapper.SyncSysUserDeptMapper;
import com.sdhs.system.syncdata.mapper.SyncSysUserMapper;
import com.sdhs.system.syncdata.service.SyncSysRoleService;
import com.sdhs.system.syncdata.service.SyncSysRoleUserService;
import com.sdhs.system.syncdata.service.SyncSysUserDeptService;
import com.sdhs.system.syncdata.service.SyncSysUserService;
import com.sdhs.system.syncdata.util.Result;
import com.sdhs.system.syncdata.util.ResultUser;
import com.sdhs.system.syncdata.util.TextUtil;
import com.sdhs.system.syncdata.util.TransforUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangmy
 * @date 2022/9/2016:46
 * @Description:
 */
@Service
public class SyncSysUserServiceImpl extends ServiceImpl<SyncSysUserMapper, SyncSysUser> implements SyncSysUserService {
    @Autowired
    private SysUserServiceImpl userService;

    @Autowired
    private SyncSysUserMapper sysUserMapper;
    @Autowired
    private SyncSysUserDeptMapper sysUserDeptMapper;

    @Autowired
    private SyncSysRoleUserService sysRoleUserService;
    @Autowired
    private SyncSysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SyncSysRoleService sysRoleService;
    @Autowired
    private SyncSysUserDeptService sysUserDeptService;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DataSource dataSource;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveUser(SyncSysUser entity) {
        String createor = entity.getBimRemoteUser();
        int insert = 0;
        Integer source = entity.getSource();
        SyncSysUser sysUser1 = new SyncSysUser();

        //如果竹云删除后再添加，会提示用户已存在的提示
        //匹配用户名、手机号、停用的账号
        QueryWrapper<SyncSysUser> queryWrapperu = new QueryWrapper<>();
        queryWrapperu.eq("phonenumber", entity.getPhonenumber());
        sysUser1 = sysUserMapper.selectOne(queryWrapperu);
        String passWord="Sdhs@123456a";
        //新手机号
        String phonenumberNew = entity.getPhonenumber();

        String id = "";
        if (sysUser1 != null) {
            id = sysUser1.getUserId().toString();
            //有停用的用户，直接启用，不再新增
            if ("1".equals(sysUser1.getStatus())) {
                String sql="update sys_user " +
                        "set status = '0' ,del_flag= '0',dept_id= '"+entity.getDeptId()+"',password='"+SecurityUtils.encryptPassword(passWord)+"',update_by='"+createor +"',update_time=now() " +
                        "where user_id = '" + id + "'";
                insert= this.jdbcTemplate.update(sql);
            } else if ("0".equals(sysUser1.getStatus())) {
                //手机号没变
                String sql="update sys_user " +
                    "set del_flag=0,dept_id='"+entity.getDeptId()+"', nick_name='"+entity.getNickName()+"', password='"+SecurityUtils.encryptPassword(passWord)+"',update_by='"+createor +"',update_time=now() " +
                    "where user_id = '" + id + "'";
                insert= this.jdbcTemplate.update(sql);
            }
            String entityDeptId = entity.getDeptId();
            if (null != entityDeptId && "0".equals(entityDeptId)) {
                entity.setDeptId(entityDeptId);
            }
            entity.setUserId(id);
            entity.setUpdateBy(createor);
            entity.setUpdateTime(new Date());
            if (null != entityDeptId && "0".equals(entityDeptId)) {
                String sql="update sys_user set del_flag= '0', password=?, dept_id=?,nick_name=?, update_by= ?,update_time=now() where user_id=?";
                this.jdbcTemplate.update(sql,SecurityUtils.encryptPassword(passWord),entity.getDeptId(),entity.getNickName(),entity.getUpdateBy(),entity.getUserId());
            }
        } else {
            //无匹配用户，新增
            entity.setPassword(SecurityUtils.encryptPassword(passWord));
            entity.setSex("0");
            if("false".equals(entity.getStatus())){
                entity.setStatus("0");
            }else{
                entity.setStatus("1");
            }
            String entityDeptId = entity.getDeptId();
            if (null != entityDeptId && "0".equals(entityDeptId)) {
                entity.setDeptId(entityDeptId);
            }
            entity.setCreateBy(createor);
            entity.setCreateTime(new Date());
            entity.setUpdateBy(createor);
            entity.setUpdateTime(new Date());
            try {
                String sql="insert into sys_user (user_id,dept_id,password,user_name,nick_name,phonenumber,status,create_by,create_time) values "+
                        "(?,?,?,?,?,?,?,?,?)";
                insert= this.jdbcTemplate.update(sql,entity.getUserId(),entity.getDeptId(),SecurityUtils.encryptPassword(passWord),entity.getUserName(),entity.getNickName(),entity.getPhonenumber(),entity.getStatus(),entity.getCreateBy(),entity.getCreateTime());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            id = String.valueOf(entity.getUserId());
        }
        Object result = TransforUtil.getResult(entity.getBimRequestId(), id, insert, "uid", 1);
        return result;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Object updateUser(SyncSysUser entity) {
        entity.setUpdateBy(entity.getBimRemoteUser());
        entity.setUpdateTime(new Date());
        String id = entity.getBimUid();
        entity.setUserId(id);
        String userId = entity.getUserId().toString();
        QueryWrapper<SyncSysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("del_flag", "0");
        SyncSysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        Result result = new Result<>();
        result.setBimRequestId(entity.getBimRequestId());
        String entityDeptId = entity.getDeptId();
        if (sysUser != null) {
            if (null != entityDeptId && "0".equals(entityDeptId)) {
                entity.setDeptId(entityDeptId);
            } else {
                entity.setDeptId(sysUser.getDeptId());
            }
            String passWord = entity.getPassword();
            if (TextUtil.isNotNull(passWord)) {
                entity.setPassword(SecurityUtils.encryptPassword(passWord));
            }

            String sql="update sys_user set " ;
                    if(TextUtil.isNotNull(entity.getNickName())){
                        sql+="nick_name= '"+entity.getNickName()+"',";
                    }

            if(TextUtil.isNotNull(entity.getPhonenumber())){
                sql+="phonenumber= '"+entity.getPhonenumber()+"',";
            }
            if(entity.getDeptId()!=null){
                sql+="dept_id= '"+entity.getDeptId()+"',";
            }
            if(TextUtil.isNotNull(entity.getStatus())){
                sql+="status ='"+entity.getStatus()+"',";
            }

            sql+=" update_time = NOW(),update_by='"+entity.getUpdateBy()+"'"+
                    " where user_id='"+entity.getUserId() + "'";

            int i = this.jdbcTemplate.update(sql);
            if (i == 1) {
                return result;
            } else {
                return result.error("修改失败");
            }
        } else {
            return result.error("用户不存在");
        }


    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object delete(String id) {
        String sql = "update sys_user set del_flag='2', status='1' where user_id = '" + id + "'";
        int i = this.jdbcTemplate.update(sql);
        Result result = new Result<>();
        if (i == 1) {
            //删除用户角色
//            String roleSql="delete from sys_user_role where user_id='" + id + "'";
//            int update = this.jdbcTemplate.update(roleSql);
            return result;
        } else {
            return result.error("删除失败");
        }
    }

    @Override
    public Object getAllUser(String random) {
        List<Integer> roleIds = sysUserMapper.getUserIds();
        ResultUser resultUser = new ResultUser();
        resultUser.setBimRequestId(random);
        if (roleIds != null && roleIds.size() != 0) {
            resultUser.setUserIdList(roleIds);
        } else {
            resultUser.setUserIdList(new ArrayList<>());
        }
        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(resultUser), "123456", "AES");
    }

    @Override
    public Object getUserById(String random, String uid) {
        SyncSysUser user11= sysUserMapper.getUserById(uid);
        List<SyncSysUser> sysUser=new ArrayList<>();
        sysUser.add(user11);

        ResultUser user = new ResultUser();
        user.setBimRequestId(random);
        Object jsonObject;
        if (sysUser != null && sysUser.size() != 0) {
            user.setUserIdList(sysUser);
            jsonObject = TransforUtil.getJsonObject(user, "account", 4);
        } else {
            user.setUserIdList(new ArrayList<>());
            jsonObject = TransforUtil.getJsonObject(user, "account", 3);
        }
        System.out.println(jsonObject);
        return BamboocloudFacade.encrypt(JSONUtil.toJsonStr(jsonObject), "123456", "AES");
    }

    @Override
    public boolean isUser(String loginName, String passWord) {
        QueryWrapper<SyncSysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", loginName);
        SyncSysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        passWord = SecurityUtils.encryptPassword(passWord);
        if (sysUser != null) {
            String pwd = sysUser.getPassword();
            if (pwd.equals(passWord)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
